package com.example.contentprovider;

import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.io.ByteArrayOutputStream;
import java.util.List;

public class FruitAdapter extends RecyclerView.Adapter<FruitViewHolder> {
    private Context context;
    private List<Fruit> fruitList;

    public FruitAdapter(Context context, List<Fruit> fruitList) {
        this.context = context;
        this.fruitList = fruitList;
    }

    @NonNull
    @Override
    public FruitViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.fruit_item, parent, false);
        FruitViewHolder holder = new FruitViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull FruitViewHolder holder, int position) {
        Fruit fruit = fruitList.get(position);
        BitmapUtil bitmapUtil = new BitmapUtil();
        holder.tvId.setText(fruit.getId());
        holder.tvName.setText(fruit.getName());
        holder.tvPrice.setText(fruit.getPrice()+"元");
        holder.tvdescription.setText(fruit.getDescription());
        holder.ivImg.setImageBitmap(fruit.getImg());
        holder.tvDel.setOnClickListener(view -> {
            MySQLiteOpenHelper helper = new MySQLiteOpenHelper(context, "fru.db", null, 1);
            SQLiteDatabase writableDatabase = helper.getWritableDatabase();
            String where = "id='" + fruit.getId()+"'";
            writableDatabase.delete("fruit", where, null);
            writableDatabase.close();
            fruitList.remove(position);
            notifyDataSetChanged();
        });

        holder.tvUpdate.setOnClickListener(view -> {
            Intent intent = new Intent();
            intent.putExtra("ID", fruit.getId());
            intent.putExtra("NAME", fruit.getName());
            intent.putExtra("PRICE", fruit.getPrice());
            intent.putExtra("DESCRIPTION", fruit.getDescription());
            bitmapUtil.saveBitmap2file(fruit.getImg(),"IMG");
            intent.setClass(context, EditActivity.class);
            context.startActivity(intent);
        });

    }

    @Override
    public int getItemCount() {
        return fruitList.size();
    }
}
